package com.hursing.tractor.baseview;

import java.util.ListIterator;

import android.graphics.Canvas;
import android.graphics.drawable.Drawable;

public class UIButton extends UIView {
	
	protected boolean mEnabled;
	
	public interface OnTouchDownListener {
		void onButtonTouchDown(UIButton button);
	}
	
	protected Drawable mEnabledBackgroundDrawable;
	protected Drawable mDisabledBackgroundDrawable;
	protected OnTouchDownListener mListener;
	
	public UIButton listener(OnTouchDownListener listener) {
		mListener = listener;
		return this;
	}

	public UIButton disabledBackgroundDrawable(Drawable drawable) {
		mDisabledBackgroundDrawable = drawable;
		return this;
	}
	
	public UIButton enabledBackgroundDrawable(Drawable drawable) {
		mEnabledBackgroundDrawable = drawable;
		return this;
	}
	
	@Override
	protected void doDraw(Canvas canvas) {
		Drawable d = mEnabled ? mEnabledBackgroundDrawable : mDisabledBackgroundDrawable;
		d.setBounds(mFrame);
		d.draw(canvas);
	}
	
	@Override
	protected boolean doOnTouchDown(int x, int y) {
		mListener.onButtonTouchDown(this);
		return true;
	}
	
	@Override
	public final boolean onTouchDown(int x, int y) {
		if (mVisible && mEnabled && mFrame.contains(x, y)) {
			if (subviews() != null) {
				ListIterator<UIView> itor = subviews().listIterator();
				while(itor.hasNext()) {
					if (itor.next().onTouchDown(x, y)) {
						return true;
					}
				}
			}
			return doOnTouchDown(x, y);
		}
		return false;
	}
	
	@Override
	public UIView enabled(boolean enabled) {
		if (mEnabled != enabled) {
			mEnabled = enabled;
			invalidate();
		}
		return this;
	}
	
	@Override
	public boolean enabled() {
		return mEnabled;
	}
}
